﻿using System;
using System.Linq;
using Xoohoo.Infrastructure;
using Xoohoo.Models;
using Xoohoo.Modules.Admin.Extensions;
using Xoohoo.Modules.Admin.Models;
using Xoohoo.Repositories;
using Xoohoo.Extensions;
using Xoohoo.Services;
using Xoohoo.Utilities.Cryptography;
using Xoohoo.ModelValidation;
using System.Web.Mvc;
using Xoohoo.Models.InputModels;

namespace Xoohoo.Modules.Admin.Services
{
    public class AdminUserService : IAdminUserService
    {
        private readonly IUserService _userService;

        public AdminUserService(IUserService userService)
        {
            this._userService = userService;
        }

        #region IAdminUserService Members

        public ModelResult ChangePassword(User user, UserChangePasswordInput input)
        {
            if (user == null)
                throw new ArgumentNullException("user");
            if (input == null)
                throw new ArgumentNullException("input");

            //判断当前密码是否输入正确
            User chkUser = _userService.GetNormalUser(user.Username, input.CurrentPassword);
            if (chkUser == null)
            {
                ModelResult modelResult = new ModelResult();
                modelResult.Errors.Add("当前密码不正确");
                return modelResult;
            }
            else
            {
                return _userService.SetPassword(chkUser.UserID, input.NewPassword);
            }
        }

        public ModelResult ChangeProfile(User user, UserChangeProfileInput input)
        {
            if (user == null)
                throw new ArgumentNullException("user");
            if (input == null)
                throw new ArgumentNullException("input");
            UserInputEdit userInput = new UserInputEdit
            {
                UserID = user.UserID,
                Username = user.Username,
                DisplayName = input.DisplayName,
                Email = input.Email,
                Password = String.Empty,//不修改密码
                PasswordConfirm = String.Empty,
                Permissions = user.Permissions != null ? from p in user.Permissions select p.PermissionID : Enumerable.Empty<Guid>(),
                Status = user.Status,
                Roles = user.Roles != null ? from r in user.Roles select r.RoleID : Enumerable.Empty<Guid>(),
                UserGroupID = user.UserGroup.UserGroupID                
            };
            _userService.Save(userInput);

            return new ModelResult();
        }

        #endregion

    }
}
